import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class HomePageView extends StatefulWidget {
  const HomePageView({super.key});

  @override
  State<StatefulWidget> createState() => HomePageState();
}

//AutomaticKeepAliveClientMixin 防止tab 切换时调用 initState
class HomePageState extends State<HomePageView>
    with AutomaticKeepAliveClientMixin {
  _showDialog(BuildContext context, String text) {
    showDialog(
        context: context,
        builder: (context) => AlertDialog(
              title: Text("请输入值" + text),
            ));
  }

  late final WebViewController _controller;

  @override
  void initState() {
    // TODO: implement setState
    super.initState();
    print("HomePageState initState");

    // #docregion platform_features
    late final PlatformWebViewControllerCreationParams params;
    // if (WebViewPlatform.instance is WebKitWebViewPlatform) {
    //   params = WebKitWebViewControllerCreationParams(
    //     allowsInlineMediaPlayback: true,
    //     mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
    //   );
    // } else {
    params = const PlatformWebViewControllerCreationParams();
    // }

    final WebViewController controller =
        WebViewController.fromPlatformCreationParams(params);
    // #enddocregion platform_features

    controller
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            debugPrint('WebView is loading (progress : $progress%)');
          },
          onPageStarted: (String url) {
            debugPrint('Page started loading: $url');
          },
          onPageFinished: (String url) {
            debugPrint('Page finished loading: $url');
          },
          onWebResourceError: (WebResourceError error) {
            debugPrint('''
Page resource error:
  code: ${error.errorCode}
  description: ${error.description}
  errorType: ${error.errorType}
  isForMainFrame: ${error.isForMainFrame}
          ''');
          },
          onNavigationRequest: (NavigationRequest request) {
            if (request.url.startsWith('https://www.youtube.com/')) {
              debugPrint('blocking navigation to ${request.url}');
              return NavigationDecision.prevent;
            }
            debugPrint('allowing navigation to ${request.url}');
            return NavigationDecision.navigate;
          },
          onUrlChange: (UrlChange change) {
            debugPrint('url change to ${change.url}');
          },
          onHttpAuthRequest: (HttpAuthRequest request) {
            // openDialog(request);
          },
        ),
      )
      ..addJavaScriptChannel(
        'Toaster',
        onMessageReceived: (JavaScriptMessage message) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(message.message)),
          );
        },
      )
      ..loadRequest(Uri.parse('https://www.baidu.com'));

    // #docregion platform_features
    // if (controller.platform is AndroidWebViewController) {
    //   AndroidWebViewController.enableDebugging(true);
    //   (controller.platform as AndroidWebViewController)
    //       .setMediaPlaybackRequiresUserGesture(false);
    // }
    // #enddocregion platform_features

    _controller = controller;
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    print("-----build刷新页面HomePageView");
    // TODO: implement build
    return Scaffold(
      backgroundColor: Colors.orange,
      appBar: AppBar(
        title: const Text("首页"),
        centerTitle: true,
        elevation: 0.0,
      ),
      body: WebViewWidget(controller: _controller),
    );
  }

  /*
  * 每个 Tab 对应的 StatefulWidget 的 State ，
  * 需要通过with AutomaticKeepAliveClientMixin ，
  * 然后重写 @override bool get wantKeepAlive => true; ，
  * 就可以实不重新构建的效果了
  * */
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

class ListViewCell extends StatelessWidget {
  final String title;
  final GestureTapCallback onClick;

  const ListViewCell({super.key, required this.title, required this.onClick});

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return ListTile(
      title: Text(
        title,
        style: const TextStyle(color: Colors.black, fontSize: 18),
      ),
      onTap: onClick,
    );
  }
}

class ListViewDivider extends StatelessWidget {
  const ListViewDivider({super.key});

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return const Divider(
      color: Colors.blue,
      height: 1,
      indent: 20,
    );
  }
}
